// noinspection t

import { toRaw } from 'vue'
import { defineStore } from 'pinia'

import { useUserStore } from './employee'
import { store } from '@/store'
import type { AppRouteRecordRaw, Menu } from '@/router/types'
import { asyncRoutes } from '@/router/routes'
import { transformRouteToMenu } from '@/router/helper/menuHelper'
import { flatMultiLevelRoutes } from '@/router/helper/routeHelper'
import { filter } from '@/utils/helper/treeHelper'
import { PageEnum } from '@/enums/pageEnum'

interface PermissionState {
  // Permission code list
  // 控件权限代码列表
  componentCodes: string[] | number[]
  // Whether the route has been dynamically added
  // 路由是否动态添加
  isDynamicAddedRoute: boolean
  // To trigger a menu update
  // 触发菜单更新
  lastBuildMenuTime: number
  // 菜单列表
  menus: Menu[]
}

export const usePermissionStore = defineStore('app-permission', {
  state: (): PermissionState => ({
    // 权限代码列表
    componentCodes: [],
    // Whether the route has been dynamically added
    // 路由是否动态添加
    isDynamicAddedRoute: false,
    // To trigger a menu update
    // 触发菜单更新
    lastBuildMenuTime: 0,
    // menu List
    // 菜单列表
    menus: [],
  }),
  getters: {
    getComponentCodes(state): string[] | number[] {
      return state.componentCodes || []
    },
    getMenus(state): Menu[] {
      return state.menus
    },
    getLastBuildMenuTime(state): number {
      return state.lastBuildMenuTime
    },
    getIsDynamicAddedRoute(state): boolean {
      return state.isDynamicAddedRoute
    },
  },
  actions: {
    setComponentCodes(componentCodes: string[]) {
      this.componentCodes = componentCodes
    },
    setMenus(list: Menu[]) {
      this.menus = list
    },
    setLastBuildMenuTime() {
      this.lastBuildMenuTime = new Date().getTime()
    },
    setDynamicAddedRoute(added: boolean) {
      this.isDynamicAddedRoute = added
    },
    resetState(): void {
      this.isDynamicAddedRoute = false
      this.componentCodes = []
      this.menus = []
      this.lastBuildMenuTime = 0
    },
    changePermissionCode(componentCodes: string[]) {
      this.setComponentCodes(componentCodes)
    },

    // 构建路由
    buildRoutesAction(): AppRouteRecordRaw[] {
      const userStore = useUserStore()
      const userHadRoutes = userStore.getUserInfo?.routePaths || []

      let routes: AppRouteRecordRaw[] = []
      const userInfo = toRaw(userStore.getUserInfo) || {}
      const routeRemoveIgnoreFilter = (route: AppRouteRecordRaw) => {
        const { meta } = route
        // ignoreRoute 为true 则路由仅用于菜单生成，不会在实际的路由表中出现
        const { ignoreRoute } = meta || {}
        // arr.filter 返回 true 表示该元素通过测试
        return !ignoreRoute
      }

      const removeHasNoPermissionFilter = (route: AppRouteRecordRaw) => {
        const { meta: { needPermission }, path } = route
        return needPermission ? userHadRoutes.includes(path) : true
      }

      /**
       * @description 根据设置的首页path，修正routes中的affix标记（固定首页）
       */
      const patchHomeAffix = (routes: AppRouteRecordRaw[]) => {
        if (!routes || routes.length === 0)
          return
        let homePath: string = PageEnum.BASE_HOME

        function patcher(routes: AppRouteRecordRaw[], parentPath = '') {
          if (parentPath)
            parentPath = `${parentPath}/`
          routes.forEach((route: AppRouteRecordRaw) => {
            const { path, children, redirect } = route
            const currentPath = path.startsWith('/') ? path : parentPath + path
            if (currentPath === homePath) {
              if (redirect) {
                homePath = route.redirect! as string
              }
              else {
                route.meta = { ...route.meta, affix: true }
                throw new Error('end')
              }
            }
            children && children.length > 0 && patcher(children, currentPath)
          })
        }

        try {
          patcher(routes)
        }
        catch (e) {
          // 已处理完毕跳出循环
        }
      }

      // 路由映射， 默认进入该case
      routes = asyncRoutes
      // 将路由转换成菜单
      const menuList = transformRouteToMenu(routes, true)
      // 移除掉 ignoreRoute: true 的路由 非一级路由
      routes = filter(routes, routeRemoveIgnoreFilter)
      // 移除掉 没有权限的非一级路由
      routes = filter(routes, removeHasNoPermissionFilter)
      // 移除掉 ignoreRoute: true 的路由 一级路由；
      routes = routes.filter(routeRemoveIgnoreFilter)
      // 移除掉 没有权限的一级路由
      routes = routes.filter(removeHasNoPermissionFilter)
      // 对菜单进行排序
      menuList.sort((a, b) => {
        return (a.meta?.orderNo ?? 0) - (b.meta?.orderNo ?? 0)
      })

      // 设置菜单列表
      this.setMenus(menuList)

      // Convert multi-level routing to level 2 routing
      // 将多级路由转换为 2 级路由
      routes = flatMultiLevelRoutes(routes)

      // 从用户中获取权限
      if (userInfo)
        this.setComponentCodes(userInfo.componentCodes)

      patchHomeAffix(routes)
      return routes
    },
  },
})

// Need to be used outside the setup
// 需要在设置之外使用
export function usePermissionStoreWithOut() {
  return usePermissionStore(store)
}
